package com.xyhuo.leetcode.january;

import com.xyhuo.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 求根节点到叶子节点数字之和
 * https://leetcode.cn/problems/sum-root-to-leaf-numbers/
 *
 * @time 2024/1/12
 */
public class SumNumbers {

    public int sumNumbers(TreeNode root) {
        if (null == root) {
            return ans;
        }
        List<Integer> list = new ArrayList<>();
        search(root, list);
        return ans;
    }

    private Integer ans = 0;

    private void search(TreeNode root, List<Integer> list) {
        if (root.left == null && root.right == null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i));
            }
            sb.append(root.val);
            Integer val = Integer.valueOf(sb.toString());
            ans += val;
        }
        if (root.left != null) {
            list.add(root.val);
            search(root.left, list);
            list.remove(list.size() - 1);
        }
        if (root.right != null) {
            list.add(root.val);
            search(root.right, list);
            list.remove(list.size() - 1);
        }
    }
}
